<template>
  <el-dialog
    :title="ruleForm.id?'编辑分类':'新增分类'"
    :visible="showDialog"
    width="50%"
    @close="handleClose"
  >
    <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="ruleForm.desc" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="图片" prop="image">
        <ImageUpload ref="userStaffPhoto" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="btnOk">确认</el-button>
      <el-button @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import { addCategories, getCategoriesById, editCategories } from '@/api/classification'
export default {
  components: {
    ImageUpload
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      ruleForm: {
        title: '',
        desc: '',
        image: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入分类名', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请输入分类描述', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async  btnOk() {
      try {
        await this.$refs.ruleForm.validate()
        const fileList = this.$refs.userStaffPhoto.fileList
        if (fileList[0] && fileList[0].status !== 'success') {
          this.$message.error('图片上传中，请稍等！')
          return
        }
        if (!fileList[0]) {
          this.$message.error('请上传图片')
          return
        }
        this.ruleForm.image = fileList[0].url
        if (this.ruleForm.id) {
          await editCategories(this.ruleForm)
          this.$emit('getCategoriesList')
        } else {
          await addCategories(this.ruleForm)
          this.$emit('getCategoriesList', 'add')
        }

        this.$message.success('操作成功')
        this.handleClose()
      } catch (error) {
        console.log(error)
      }
    },
    async  getCategories(id) {
      const { data } = await getCategoriesById(id)
      this.ruleForm = data
      this.$refs.userStaffPhoto.fileList.push({ url: data.image })
    },
    handleClose() {
      this.$refs.ruleForm.resetFields()
      this.ruleForm = {
        title: '',
        desc: '',
        image: ''
      }
      this.$refs.userStaffPhoto.fileList = []
      this.$emit('update:showDialog', false)
    }
  }
}
</script>

<style>

</style>
